<?php

namespace App\Http\Controllers;

use App\Models\Records;
use App\Models\Shares;
use App\Models\Videos;
use App\Models\VideosCollect;
use App\Models\VideosCount;
use App\Models\VideosZan;
use App\Models\Views;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

/**
 * 视频相关
 * Class VideoController
 * @package App\Http\Controllers
 */
class VideoController extends Controller{
    /**
     * 列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index (Request $request){


        try {
            $start = microtime(true);
            $params = [
                'chanel_id' => (int)$request->get('chanel_id',0),//频道
                'option' => (int)$request->get('option',1),//推荐
                'follow' => (int)$request->get('follow',0),//关注
            ];
            $rand = rand(1, 30);
            $lists = Videos::select('id','title','thumb','time','view','link','cate_id','status','comment_count','chanel_id','created_at')
                ->where(function($query) use($params,$rand){
                    if ($params['chanel_id']){
                        $query->where('chanel_id',$params['chanel_id']);
                    }
                    if($params['follow']){
                        $query->where('good',Videos::GOOD_1);
                    }
                    if ($params['option']){
                        $query->where('option',Videos::OPTION_1)->where('rand_cate', $rand);
                    }
                    $query->where('status',Videos::STATUS_1);
                })
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name','avatar')->get();
                }])
                ->orderBy('sort','DESC')
                ->paginate(10);
            $end = microtime(true);
            Log::info('响应时间：'.($end-$start));
            return $this->returnJson(0,'',$lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }


    /**
     * 详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function info(Request $request){

        $user_id = auth()->guard('api')->id();
        try {
            $id = (int)$request->get('id');
            $shareuid = (int)$request->get('shareuid',0);
            if (empty($id)){
                return $this->returnJson(1,'参数错误');
            }
            $info = Videos::where('status',Videos::STATUS_1)
                ->select('id','title','thumb','time','userid','view','link','cate_id','status','chanel_id','created_at','comment_count','collect_count','zan_count','share_count')
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name','avatar')->get();
                }])
                ->with(['zan' => function ($query) use ($user_id,$id) {
                    $query->where(['video_id'=>$id,'user_id'=>$user_id])->get();
                }])
                ->with(['collect' => function ($query) use ($user_id,$id) {
                    $query->where(['video_id'=>$id,'user_id'=>$user_id])->get();
                }])
                ->find($id);
            if(!$info){
                return $this->returnJson(1,'数据信息不存在');
            }
            $video = $this->getVideo($info['link']);
            $info['play_link'] = $video['link'];
            //匹配腾讯视频的vid
            $result = preg_match_all('/\/([0-9a-zA-Z]+).html/', $info['link'], $matchs);
            if ($result) {
                $matchs = array_flatten($matchs);
            }
            $vid = $matchs[1] ?? '';
            $info['vid'] = $vid;
            DB::transaction(function () use($id,$info,$user_id,$shareuid){
                //增加视频当天人气记录
                $view = Views::where('video_id',$id)
                    ->whereDate('created_at',Carbon::now()->format('Y-m-d'))
                    ->first();
                if($view){
                    $view->increment('num');
                }else{
                    Views::create([
                        'video_id' => $id,
                        'created_at' => Carbon::now(),
                        'num' => 1
                    ]);
                }
                //增加总人气记录
                $info->increment('view');
                //增加用户浏览记录
                $record = Records::where('video_id',$id)
                    ->where('userid',$user_id)
                    ->whereDate('created_at',Carbon::now()->format('Y-m-d'))
                    ->first();
                if(!$record){
                    Records::create([
                        'video_id' => $id,
                        'userid' => auth()->guard('api')->id(),
                        'created_at' => Carbon::now(),
                    ]);
                }
                //更新个人任务信息
                $this->finishTask($user_id,'watch',$id);
                //增加视频统计数据信息
                (new VideosCount())->updateCount($info,'views');   //阅读量

                if($shareuid){
                    //增加视频分享数据信息 in
                    (new VideosCount())->updateCount($info,'share_in');

                    $shareData = ['video_id'=>$id,'user_id'=>$user_id];
                    $shareID = Shares::where(['video_id'=>$id,'user_id'=>$user_id])->get()->first();
                    //判断是否是有效分享
                    if(!$shareID){
                        //增加总有效分享数
                        $info->increment('share_count');
                        $shareData['created_at'] = Carbon::now();
                        Shares::create($shareData);
                    }
                }
            });
            return $this->returnJson(0,'success',$info);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }


    /**
     * 视频播放详情随机列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function list(Request $request){
        try {
            $id = (int)$request->get('id');
            if (empty($id)) {
                return $this->returnJson(1, '参数错误');
            }
            $rand = rand(1, 30);
            $lists = Videos::select('id', 'title', 'thumb', 'time', 'view')
                ->where('id', '<>', $id)
                ->where('rand_cate', $rand)
                ->where('status', Videos::STATUS_1)
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name', 'avatar')->get();
                }])
                ->orderBy('sort', 'DESC')
                ->paginate(10);
            return $this->returnJson(0, '', $lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

    /**
     * 分享
     * @return \Illuminate\Http\JsonResponse
     */
    public function share(){
        $id = (int)request('id');
        if (empty($id)) {
            return $this->returnJson(1, '参数错误');
        }
        $info = Videos::find($id);
        if(!$info){
            return $this->returnJson(1, '数据不存在');
        }
        $info->increment('share');
        //增加视频分享数据信息 out
        (new VideosCount())->updateCount($info,'share_out');
        return $this->returnJson(0);
    }


    public function randList(){
        try {
            $id = (int)request('id');
            if (empty($id)) {
                return $this->returnJson(1, '参数错误');
            }
            $lists = Videos::select('id', 'title', 'thumb', 'time', 'view','cate_id')
                ->where('id', '<>', $id)
                ->where('status', Videos::STATUS_1)
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name', 'avatar')->get();
                }])
                ->take(20)
                ->inRandomOrder()
                ->get();
            return $this->returnJson(0, '', $lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }



    /**
     * 视频点赞
     */
    public function zan(){
        $data['video_id'] = (int)request('id',0); //视频ID
        $data['user_id'] = auth()->guard('api')->id();
        $data['status'] = 1;

        $findID = VideosZan::where($data)->first();
        if($findID){
            //update
            $update = $findID->update($data);
            if($update){
                //更新个人任务信息
                $this->finishTask($data['user_id'],'video_zans',$findID['id']);
                $info = Videos::find($data['video_id']);
                //更新统计数
                $info->increment('zan_count');
                //增加视频统计数据信息
                (new VideosCount())->updateCount($info,'zans');
                return $this->returnJson(0);
            }
            return $this->returnJson(1,'error');
        }
        // create
        $create = VideosZan::create($data);
        if($create){
            //更新个人任务信息
            $this->finishTask($data['user_id'],'video_zans',$create['id']);
            $info = Videos::find($data['video_id']);
            //更新统计数
            $info->increment('zan_count');
            //增加视频统计数据信息
            (new VideosCount())->updateCount($info,'zans');
            return $this->returnJson(0);
        }
        return $this->returnJson(1,'error');
    }

    /**
     * 视频收藏
     */
    public function collect(){

        $data['video_id'] = (int)request('id',0); //视频ID
        $data['user_id'] = auth()->guard('api')->id();

        $findID = VideosCollect::where($data)->first();
        if($findID){
            $data['status'] = 1;
            //update
            if($findID['status'] == 1){
                $data['status'] = 0;
            }
            $update = $findID->update($data);
            if($update){
                $msg = '已成功收藏';
                if($data['status'] == 0){
                    //更新统计数
                    $findVideo = Videos::find($data['video_id']);
                    if($findVideo['collect_count'] > 0){
                        $findVideo->decrement('collect_count');
                    }
                    $msg = '已取消收藏';
                }else{
                    //更新个人任务信息
                    $this->finishTask($data['user_id'],'video_collects',$findID['id']);
                    //更新统计数
                    $findVideo = Videos::find($data['video_id']);
                    $findVideo->increment('collect_count');
                }
                //增加视频统计数据信息
                (new VideosCount())->updateCount($findVideo,'collects');
                return $this->returnJson(0,$msg);
            }
            return $this->returnJson(1,'error');
        }
        // create
        $data['status'] = 1;
        $create = VideosCollect::create($data);
        if($create){
            //更新个人任务信息
            $this->finishTask($data['user_id'],'video_collects',$create['id']);
            //增加视频统计数据信息
            $findVideo = Videos::find($data['video_id']);
            (new VideosCount())->updateCount($findVideo,'collects');
            return $this->returnJson(0,'已成功收藏');
        }
        return $this->returnJson(1,'error');
    }

    /**
     * 获取个人收藏列表（视频）
     * @return \Illuminate\Http\JsonResponse
     */
    public function collectList(){
        $data['user_id'] = auth()->guard('api')->id();
        $data['status'] = 1;

        $videos = VideosCollect::where($data)->with('video')->orderBy('updated_at','DESC')->get();
        $new = [];
        foreach ($videos as $list){
            $new[$list->updated_at->format('Y年m月d日')][] = $list;
        }
        return $this->returnJson(0,'',$new);
    }

    /**
     * 获取首页视频轮播列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function wheelList(){
        $lists = Videos::where('wheel',1)->get();
        return $this->returnJson(0,'',$lists);
    }


}
